package cn.uin.domain.auth.service.user.login.jwt.handle;

import cn.uin.domain.auth.adapter.repository.IAuthRepository;
import cn.uin.domain.auth.model.entity.UserInfoDetailEntity;
import cn.uin.domain.auth.service.user.login.handle.AbstractAuthenticationSuccessHandler;
import cn.uin.types.enums.ResponseCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: uIn
 * @Date: 2025/10/19 - 10 - 19 - 21:58
 * @Description: 自定义认证成功返回
 * @version: 1.0
 */
@Slf4j
@Component
public class CustomJWTAuthenticationSuccessHandler extends AbstractAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private IAuthRepository authRepository;

    private final static String RESPONSE_TYPE= "application/json;charset=utf-8";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        saveLoginLog(request, authentication, 1);
        // 获取登陆成功用户信息
        UserInfoDetailEntity authenticationPrincipal = (UserInfoDetailEntity) authentication.getPrincipal();

        // token写入redis
        Map<String, Object> map = new HashMap<>();
        if (CollectionUtils.isEmpty(authenticationPrincipal.getRoles())) {
            List<String> roles = authenticationPrincipal.getRoles().stream().map(item -> item.getRoleCode()).collect(Collectors.toList());
            map.put("roles", roles);
        }
        if (!CollectionUtils.isEmpty(authenticationPrincipal.getMenus())) {
            List<String> menus = authenticationPrincipal.getMenus().stream().map(item -> item.getMenuCode()).collect(Collectors.toList());
            map.put("menus", menus);
        }

        String token = authRepository.saveUserToken(authenticationPrincipal.getUsername(), map);
        // 构建返回对象
        Map<String, Object> resultMap = new HashMap<>(3);
        resultMap.put("code", ResponseCode.SUCCESS.getCode());
        resultMap.put("message", "登陆成功！");
        resultMap.put("token", token);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(RESPONSE_TYPE);
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(resultMap));
    }
}
